#include "monitorpointwidget.h"

MonitorPointWidget::MonitorPointWidget(const SerialConfig &config,QWidget *parent) : QWidget(parent)
{
    m_config = config;

    // 创建顶部控制栏
    QHBoxLayout *topLayout = new QHBoxLayout();
    topLayout->setContentsMargins(0, 0, 0, 0);

    // 添加标题
    QLabel *titleLabel = new QLabel(config.name + " (" + config.portName + ")", this);
    titleLabel->setFont(QFont("Arial", 12, QFont::Bold));
    topLayout->addWidget(titleLabel);

    // 添加状态指示器
    m_statusLabel = new QLabel("状态: 未连接", this);
    m_statusLabel->setStyleSheet("color: red;");
    topLayout->addWidget(m_statusLabel);

    // 添加关闭按钮
    m_closeButton = new QPushButton("关闭", this);
    m_closeButton->setFixedSize(60, 25);
    connect(m_closeButton, &QPushButton::clicked, this, &MonitorPointWidget::closeMonitor);
    topLayout->addWidget(m_closeButton);

    // 创建图表区域 - 左右分栏
    QHBoxLayout *chartLayout = new QHBoxLayout();

    // 创建折线图
    m_lineChart = new LineChartWidget(this);
    chartLayout->addWidget(m_lineChart, 1);

    // 创建柱状图
    m_barChart = new BarChartWidget(this);
    chartLayout->addWidget(m_barChart, 1);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(topLayout);
    mainLayout->addLayout(chartLayout);

    // 设置边框样式
    setStyleSheet("MonitorPointWidget { border: 1px solid #cccccc; border-radius: 4px; margin: 5px; }");
}


void MonitorPointWidget::setDataReader(DataReader *reader){
    m_reader = reader;
    if (m_reader) {
        connect(m_reader, &DataReader::dataReady, this, &MonitorPointWidget::updateCharts);
        connect(m_reader, &DataReader::errorOccurred, this, &MonitorPointWidget::handleError);

        // 尝试打开串口
        if (m_reader->startReading()) {
            m_statusLabel->setText("状态: 已连接");
            m_statusLabel->setStyleSheet("color: green;");
        } else {
            m_statusLabel->setText("状态: 连接失败");
            m_statusLabel->setStyleSheet("color: red;");
        }
    }
}


void MonitorPointWidget::updateCharts(const DataPoint &data)
{
    m_lineChart->updateChart(data);
    m_barChart->updateChart(data);
    emit sendDataPoint(data);
    // 更新状态标签为已连接
    if (m_statusLabel->text() != "状态: 已连接") {
        m_statusLabel->setText("状态: 已连接");
        m_statusLabel->setStyleSheet("color: green;");
    }
}


void MonitorPointWidget::handleError(const QString &error)
{
    m_statusLabel->setText("状态: 错误 - " + error);
    m_statusLabel->setStyleSheet("color: red;");
}


void MonitorPointWidget::closeMonitor()
{
    if (m_reader)
        m_reader->stopReading();
    emit monitorClosed(this);
    deleteLater();
}
